package com.by.service.impl;

import com.by.bean.Car;
import com.by.service.CarService;
import com.by.utils.RedisUtils;
import org.springframework.stereotype.Service;

import java.util.*;

//@Service
public class CarServiceImpl2 implements CarService {
    RedisUtils redisUtils;

    public CarServiceImpl2(RedisUtils redisUtils) {
        this.redisUtils = redisUtils;
    }

    @Override
    public void addCar(Car car) {
        String key = "car:userTest:1:goods:" + car.getId();
        //判断是否存在
        Object tmp = redisUtils.get(key);
        if (tmp == null) {
            //不存在，加入购物车
            redisUtils.set(key, car);
        } else {
            //存在，更新购物车
            Car tmpCar = (Car) tmp;
            int num = tmpCar.getNum();
            num++;
            tmpCar.setNum(num);
            redisUtils.set(key, car);
        }
    }

    @Override
    public List<Car> getCarList() {
        List<Car> list = new ArrayList<Car>();
        //获取该用户所有商品的key
        Set<String> keys = redisUtils.keys("car:userTest:1:goods:*");
        Iterator<String> it = keys.iterator();
        while (it.hasNext()) {
            String key = it.next();//一个商品的key
            Object obj = redisUtils.get(key);
            list.add((Car) obj);

        }
        return list;
    }
}
